package com.demo.app.testep;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.google.android.exoplayer2.ControlDispatcher;
import com.google.android.exoplayer2.DefaultLoadControl;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
import com.google.android.exoplayer2.source.ads.AdsMediaSource;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.ui.DefaultTimeBar;
import com.google.android.exoplayer2.ui.PlayerControlView;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.upstream.cache.CacheUtil;
import com.google.android.exoplayer2.util.EventLogger;
import com.google.android.exoplayer2.util.Util;

import androidx.annotation.NonNull;

public class MainActivity extends Activity {

    private static final String TAG = MainActivity.class.getSimpleName();
    PlayerView playerview;
    SimpleExoPlayer simpleExoPlayer;


    String url = "https://vfx.mtime.cn/Video/2020/03/25/mp4/200325074819698533.mp4";



    RelativeLayout layoutVideo;

    Handler handler;

    private boolean isLandscape; //true表示横屏

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();



    }

    private void init() {
        playerview = findViewById(R.id.playerview);
        layoutVideo = findViewById(R.id.layout_video);

        PlayerControlView playerControlView =  playerview.findViewById(R.id.exo_controller);
        playerControlView.setProgressUpdateListener(new PlayerControlView.ProgressUpdateListener() {
            @Override
            public void onProgressUpdate(long position, long bufferedPosition) {
                Log.e(TAG, "onProgressUpdate: "+position );
            }
        });
        Log.e(TAG, "init: "+playerControlView );

        findViewById(R.id.but_fullscreen).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }
        });

        simpleExoPlayer = ExoPlayerFactory.newSimpleInstance(this);


        DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(this,
                Util.getUserAgent(this, "com.demo.app.testep"));

        MediaSource videoSource =
                new ProgressiveMediaSource.Factory(dataSourceFactory)
                        .createMediaSource(Uri.parse(url));

        //simpleExoPlayer.addAnalyticsListener(new EventLogger(new DefaultTrackSelector()));
        simpleExoPlayer.prepare(videoSource);
        simpleExoPlayer.setPlayWhenReady(true);

        playerview.setPlayer(simpleExoPlayer);



        playerview.setControlDispatcher(new ControlDispatcher() {
            @Override
            public boolean dispatchSetPlayWhenReady(Player player, boolean playWhenReady) {
                player.setPlayWhenReady(playWhenReady);
                return true;
            }

            @Override
            public boolean dispatchSeekTo(Player player, int windowIndex, long positionMs) {
                player.seekTo(windowIndex, positionMs);
                return true;
            }

            @Override
            public boolean dispatchSetRepeatMode(Player player, @Player.RepeatMode int repeatMode) {
                player.setRepeatMode(repeatMode);
                return true;
            }

            @Override
            public boolean dispatchSetShuffleModeEnabled(Player player, boolean shuffleModeEnabled) {
                player.setShuffleModeEnabled(shuffleModeEnabled);
                return true;
            }

            @Override
            public boolean dispatchStop(Player player, boolean reset) {
                player.stop(reset);
                return true;
            }
        });



        handler = new Handler(){

            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);

                if(msg.what ==1){
                    handler.postDelayed(runnable,2000);
                }
            }
        };
        handler.postDelayed(runnable,2000);
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {


            if(playerview.getPlayer().isPlaying()){
                Log.e(TAG, "run: "+playerview.getPlayer().getCurrentPosition() );
            }

            Message msg = Message.obtain();
            msg.what = 1;
            handler.sendMessage(msg);

        }
    };

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        if( Configuration.ORIENTATION_LANDSCAPE == newConfig.orientation){
            //横屏
            isLandscape = true;
            LinearLayout.LayoutParams par = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
            layoutVideo.setLayoutParams(par);
            layoutVideo.setBackgroundColor(Color.BLACK);


            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT
            );
            layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);

            playerview.setLayoutParams(layoutParams);

        }else if(Configuration.ORIENTATION_PORTRAIT == newConfig.orientation){
            Log.e(TAG,"竖屏****************************");

            isLandscape = false;

            LinearLayout.LayoutParams par = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, toDp(210));

            layoutVideo.setLayoutParams(par);



        }



    }



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if(keyCode == KeyEvent.KEYCODE_BACK && isLandscape){
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    public  int toDp(int px){
        return (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,px,

             getResources().getDisplayMetrics());

    }
}
